package com.wjh.wn.taximanager

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.webkit.JavascriptInterface
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone

class MainActivity : androidx.activity.ComponentActivity() {

    private var updateCount = 0

    private lateinit var locationManager: LocationManager
    private var locationListener: LocationListener? = null
    private lateinit var handler: Handler
    private var timeoutRunnable: Runnable? = null

    // UI 组件
    private lateinit var webView: WebView

    // 定位参数
    private val minTimeMs = 1000L // 更新间隔 1秒
    private val minDistanceM = 1f // 最小位移 1米
    private var isReceivingLocation = false

    // State Management
    private enum class GpsState {
        IDLE, ACQUIRING, TRACKING, GPS_DISABLED, TIMEOUT
    }
    private var currentState = GpsState.IDLE

    // 权限请求码
    companion object {
        private const val LOCATION_PERMISSION_REQUEST_CODE = 1001
        private const val GPS_TIMEOUT_MS = 30000L
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initViews()
        setupLocationManager()
        handler = Handler(Looper.getMainLooper())
    }

    // 修正接口类定义
    inner class WebInterface(private val context: Context) {
        @JavascriptInterface
        fun toggleLocation() {
            // 必须切换到主线程操作
            (context as Activity).runOnUiThread {
                when (currentState) {
                    GpsState.IDLE, GpsState.GPS_DISABLED, GpsState.TIMEOUT -> startLocationProcess()
                    GpsState.ACQUIRING, GpsState.TRACKING -> stopLocationUpdates()
                }
            }
        }
    }

    // 初始化视图 =================================================================
    private fun initViews() {
        // 初始化 WebView
        webView = findViewById(R.id.webView)

        // 基本配置
        val webSettings = webView.settings
        webSettings.javaScriptEnabled = true  // 启用 JavaScript
        webSettings.domStorageEnabled = true  // 启用 DOM 存储

        // 绑定接口（关键修正）
        webView.addJavascriptInterface(WebInterface(this), "AndroidBridge")

        //加载本地 HTML 文件
        webView.loadUrl("file:///android_asset/speed.html")

        webView.webViewClient = object : WebViewClient() {
            override fun onReceivedHttpError(
                view: WebView?,
                request: WebResourceRequest?,
                errorResponse: WebResourceResponse?
            ) {
                Toast.makeText(this@MainActivity, "加载页面出错", Toast.LENGTH_SHORT).show()
            }
            override fun onPageFinished(view: WebView?, url: String?) {
                // 页面加载完成后初始化状态
                updateGpsState(currentState)
            }
        }
    }

    // 设置定位管理器 ==============================================================
    private fun setupLocationManager() {
        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
    }

    // 核心定位逻辑 ================================================================
    private fun startLocationProcess() {
        if (!isGpsEnabled()) {
            showGpsDisabledAlert()
            return
        }
        // 立即更新状态为 ACQUIRING
        updateGpsState(GpsState.ACQUIRING)
        checkLocationPermission()
    }

    @SuppressLint("MissingPermission")
    private fun startGpsTracking() {
        initLocationListener()
        locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            minTimeMs,
            minDistanceM,
            locationListener!!
        )
        startTimeoutTimer()
        updateGpsState(GpsState.ACQUIRING)
        showLastKnownLocation()
    }

    // 状态更新方法（明确实现的 updateGpsState）=====================================
    private fun updateGpsState(newState: GpsState) {
        currentState = newState
        val (message, color) = when (newState) {
            GpsState.IDLE -> Pair("等待启动", "#9E9E9E")
            GpsState.ACQUIRING -> Pair("正在搜索卫星...", "#2196F3")
            GpsState.TRACKING -> Pair("定位进行中", "#4CAF50")
            GpsState.GPS_DISABLED -> Pair("GPS未启用", "#F44336")
            GpsState.TIMEOUT -> Pair("信号获取超时", "#FF9800")
        }

        // 修正字符串转义
        val jsCode = "updateStatus('${message}', '${color}')"
        webView.evaluateJavascript(jsCode, null)
    }

    // 超时检测逻辑（明确添加）=======================================================
    private fun startTimeoutTimer() {
        timeoutRunnable = Runnable {
            if (!isReceivingLocation) {
                updateGpsState(GpsState.TIMEOUT)
                Toast.makeText(this, "无法在30秒内获取GPS信号", Toast.LENGTH_LONG).show()
            }
        }
        handler.postDelayed(timeoutRunnable!!, GPS_TIMEOUT_MS)
    }

    private fun cancelTimeoutTimer() {
        timeoutRunnable?.let {
            handler.removeCallbacks(it)
            timeoutRunnable = null
        }
    }

    // 定位监听器 ==================================================================
    private fun initLocationListener() {
        locationListener = object : LocationListener {
            override fun onLocationChanged(location: Location) {
                handleLocationUpdate(location)
            }

            override fun onProviderDisabled(provider: String) {
                updateGpsState(GpsState.GPS_DISABLED)
                isReceivingLocation = false
            }

            override fun onProviderEnabled(provider: String) {
                updateGpsState(GpsState.ACQUIRING)
            }

            override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
                if (status == 0) updateGpsState(GpsState.ACQUIRING)
            }
        }
    }

    // 数据处理 ====================================================================
    private fun handleLocationUpdate(location: Location) {
        isReceivingLocation = true
        cancelTimeoutTimer()
        updateLocationUI(location)
        updateGpsState(GpsState.TRACKING)
        // 计数器递增
        updateCount++
        // 更新 HTML 页面中的计数显示
        updateUpdateCount()
    }

    // 定义计数更新方法
    private fun updateUpdateCount() {
        val jsScript = "updateUpdateCount($updateCount)"
        webView.evaluateJavascript(jsScript, null)
    }

    private fun updateLocationUI(location: Location) {
        runOnUiThread {
            // 速度（突出显示）

            val speedKmh = formatSpeed(location.speed)
            val jsScript = """
            updateGauge(${speedKmh});
            document.getElementById('latitude').textContent = '${"%.6f".format(location.latitude)}';
            document.getElementById('longitude').textContent = '${"%.6f".format(location.longitude)}';
            document.getElementById('altitude').textContent = '${"%.2f m".format(location.altitude)}';
            document.getElementById('accuracy').textContent = '${"%.1f m".format(location.accuracy)}';
            document.getElementById('bearing').textContent = '${simpleConvertBearing(location.bearing)}';
            document.getElementById('time').textContent = '${formatTimestamp(location.time)}';
        """.trimIndent()

            webView.evaluateJavascript(jsScript, null)
        }
    }

    // 数据格式化 ==================================================================
    private fun formatSpeed(speedMps: Float) = "%.0f".format(speedMps * 3.6f)
    private fun formatAltitude(altitude: Double) = "%.2f".format(altitude)

    // 权限管理 ====================================================================
    private fun checkLocationPermission() {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestLocationPermission()
        } else {
            startGpsTracking()
        }
    }

    private fun requestLocationPermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
            LOCATION_PERMISSION_REQUEST_CODE
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE && grantResults.isNotEmpty()) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startGpsTracking()
            } else {
                Toast.makeText(this, "需要位置权限", Toast.LENGTH_LONG).show()
            }
        }
    }

    // 停止定位 ====================================================================
    private fun stopLocationUpdates() {
        locationListener?.let {
            locationManager.removeUpdates(it)
            cancelTimeoutTimer()
            updateGpsState(GpsState.IDLE)
            isReceivingLocation = false
        }
        updateCount = 0;
    }

    // 辅助方法 ====================================================================
    private fun isGpsEnabled() = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)

    private fun showGpsDisabledAlert() {
        AlertDialog.Builder(this)
            .setTitle("GPS未启用")
            .setMessage("需要开启GPS才能进行定位")
            .setPositiveButton("去设置") { _, _ ->
                startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 将时间戳转换为易读的时间字符串
     * @param timestamp 时间戳（毫秒）
     * @param pattern 时间格式，默认"yyyy-MM-dd HH:mm:ss"
     * @return 格式化后的时间字符串
     */
    fun formatTimestamp(
        timestamp: Long,
        pattern: String = "yyyy-MM-dd HH:mm:ss"
    ): String {
        return try {
            val sdf = SimpleDateFormat(pattern, Locale.getDefault())
            sdf.timeZone = TimeZone.getDefault() // 使用系统时区
            sdf.format(Date(timestamp))
        } catch (e: Exception) {
            "Invalid timestamp"
        }
    }

    // 简化版（8方向）
    fun simpleConvertBearing(degrees: Float): String {
        val directions = arrayOf("北", "东北", "东", "东南", "南", "西南", "西", "西北")
        val index = ((degrees + 22.5) % 360 / 45).toInt()
        return directions[index % 8]
    }

    @SuppressLint("MissingPermission")
    private fun showLastKnownLocation() {
        locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)?.let {
            updateLocationUI(it)
        }
    }

    // 生命周期管理 ================================================================
    override fun onPause() {
        super.onPause()
        stopLocationUpdates()
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        // 在这里处理屏幕旋转逻辑，例如调整布局等
    }
}

